package com.dormitory.management.system.listener;

import com.dormitory.management.system.utils.EmailUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.nio.charset.StandardCharsets;

public class RedisExpiredListenter extends KeyExpirationEventMessageListener {
    private static final Logger LOGGER = LoggerFactory.getLogger(RedisExpiredListenter.class);

    public RedisExpiredListenter(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String channel = new String(message.getChannel(), StandardCharsets.UTF_8);
        //过期的key
        String key = new String(message.getBody(),StandardCharsets.UTF_8);
        System.err.println(message.getBody()+" "+message.getChannel());
        JavaMailSenderImpl sender = EmailUtil.createMailSender("956259000@qq.com", "bbpinjtqrklmbdab");
        String[] strings = key.split("\\*\\*\\*");
        LOGGER.info("redis key 过期：pattern={},channel={},key={}",new String(pattern),channel,key);
        if(strings[3].equals("null")){
            EmailUtil.sendHtmlMail(sender,strings[0],strings[1],strings[2],null);
        }else
            EmailUtil.sendHtmlMail(sender,strings[0],strings[1],strings[2],strings[3]);

    }
}
